/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package webservices;

import Entities.Resourcecategory;
import constants.Consts;
import helpers.Debug;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.persistence.EntityManager;
import javax.persistence.TypedQuery;
import javax.ws.rs.Path;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.UriInfo;
import org.codehaus.jettison.json.JSONArray;
import org.codehaus.jettison.json.JSONException;
import org.codehaus.jettison.json.JSONObject;
import rhserver.MainController;

/**
 * REST Web Service
 *
 * @author Bari
 */
@Path("getresourcecategories")
public class Getresourcecategories extends AbstractWebService {

    @Context
    private UriInfo context;

    /**
     * Creates a new instance of Getresourcecategories
     */
    public Getresourcecategories() throws Exception {
        super();
    }

    private List<Resourcecategory> getRersourceCategoriesJPA(EntityManager em) {
        
        TypedQuery<Resourcecategory> query = em.createNamedQuery("Resourcecategory.findAll", Resourcecategory.class);
        List<Resourcecategory> categories = query.getResultList();
        return categories;


    }

    private JSONObject getCategories(EntityManager em) {
        try {
            JSONObject response = new JSONObject();
            List<Resourcecategory> categories = getRersourceCategoriesJPA(em);
            JSONArray jsonArray = new JSONArray();
            for (Resourcecategory res : categories) {
                jsonArray.put( res.toJson());
            }
            response.put(Consts.JSON_ARRAY, jsonArray);
            return response;

        } catch (JSONException ex) {
            Logger.getLogger(GetResourceList.class.getName()).log(Level.SEVERE, null, ex);
            return null;
        }
    }

    @Override
    protected String processJsonMessage(String jsonMessage) {
        EntityManager em = MainController.getInstance().getEntityManager();
        try {
            Debug.logMessage("processJsonMessage", "Creating Json from db");
            JSONObject response = getCategories(em);
            response.put(Consts.JSON_MESSAGE_CODE, Consts.RESPONSE_RESULT);
            Debug.logMessage("processJsonMessage", "message: " + response.toString());
            em.close();
            return response.toString();

        } catch (JSONException ex) {
            Logger.getLogger(Getresourcecategories.class.getName()).log(Level.SEVERE, null, ex);
            em.close();
            return null;
        }
    }
}
